<template>
  <div @click="handleClick" v-show="show" class="to-top-container">上</div>
</template>

<script setup lang="ts">
import { onUnmounted, ref, getCurrentInstance, type ComponentPublicInstance } from 'vue'
const proxy: ComponentPublicInstance<any> = getCurrentInstance()?.proxy
const show = ref(false)
//当组件切换时，重新监听mainScroll
proxy.$mybus.on('changeURL', () => {
  show.value = false
  proxy.$mybus.on('mainScroll', handleScroll)
})
proxy.$mybus.on('mainScroll', handleScroll)
function handleScroll(dom: any) {
  if (!dom) {
    show.value = false
    return
  }
  show.value = dom.scrollTop >= 500
}
function handleClick() {
  // 回到顶部
  proxy.$mybus.emit('setMainScroll', 0)
}
onUnmounted(() => {
  console.log('销毁')
  proxy.$mybus.off('changeURL')
  proxy.$mybus.off('mainScroll', handleScroll)
})
</script>

<style scoped lang="scss">
@import '@/styles/var.scss';

.to-top-container {
  background: #fff;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  position: fixed;
  z-index: 99;
  right: 50px;
  bottom: 50px;
  cursor: pointer;
  line-height: 50px;
  color: #515767;
  text-align: center;
  box-shadow: rgba(50, 50, 50, 0.04) 0px 2px 8px 0px;
}
</style>
